<?php
$servername = 'localhost';
$username = 'username';
$password = 'password';
$dbname = 'testDB';

// 创建连接
$connect = mysqli_connect($servername, $username, $password);
 
// 检测连接
if (!$connect) {
    die("Connection failed: " . mysqli_connect_error() . "<br />");
}
// 选择数据库
mysqli_select_db($connect, $dbname);
// 设置编码，防止中文乱码
mysqli_query($connect, "set names utf8");

// 查询用户数据并输出
$sql = 'SELECT id, name, children, level FROM fatherclass ORDER BY id';
$retval = mysqli_query($connect, $sql);
$result['success'] = false;
$result['message'] = '';
if (!$retval) {
    die('ERROR: ' . mysqli_error($connect));
} else {
    // 使用 mysqli_fetch_assoc 获取数据
    $i = 0;
    while ($row = mysqli_fetch_assoc ($retval)) {
        $result['docs'][$i]["id"] = $row['id'];
        $result['docs'][$i]["name"] = urlencode($row['name']);// 将名称进行 URL 编码，防止转化为 json 时乱码

        // 查询收藏数据
        $sqlCL = 'SELECT id, name, father, children, level FROM ' . $row['children'] . ' ORDER BY id';
        $retvalCL = mysqli_query($connect, $sqlCL);
        if (!$retvalCL) {
        die('ERROR: ' . mysqli_error($connect));
        } else {
            $j = 0;
            while ($rowCL = mysqli_fetch_assoc ($retvalCL)) {
                $result['docs'][$i]['children'][$j]['id'] = $rowCL['id'];
                $result['docs'][$i]['children'][$j]['name'] = urlencode($rowCL['name']);
                $result['docs'][$i]['children'][$j]['father'] = $rowCL['father'];
                $result['docs'][$i]['children'][$j]['children'] = $rowCL['children'];
                $result['docs'][$i]['children'][$j]['level'] = $rowCL['level'];

                $j += 1;
            }
        }
        $result['docs'][$i]["level"] = $row['level'];
        $i += 1;
    }
    $result['success'] = true;
    $result['message'] = urlencode('查询成功!');
    // 释放内存
    mysqli_free_result($retval);
    mysqli_free_result($retvalCL);
}
// print_r($result);
// 将数组转为 json 数据，再用 urldecode URL 解码
echo urldecode(json_encode($result));